/*
 * Copyright 2013 Sigurd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package de.digiway.rapidbreeze.server.model.download;

import de.digiway.rapidbreeze.shared.rest.download.DownloadStatus;
import java.util.ArrayList;
import java.util.List;

/**
 *
 * @author Sigurd
 */
public class ThrottleSupport {

    private DownloadManager downloadManager;
    private DownloadManagerListenerHelper downloadManagerListenerHelper;
    private long throttle = 0;

    public ThrottleSupport(DownloadManager downloadManager) {
        this.downloadManager = downloadManager;
        this.downloadManagerListenerHelper = new DownloadManagerListenerHelper();

        this.downloadManager.addListener(downloadManagerListenerHelper);
    }

    private void distributeSpeedThrottle() {
        List<Download> activeDownloads = new ArrayList<>();
        for (Download download : downloadManager.getDownloads()) {
            if (download.getDownloadStatus().equals(DownloadStatus.RUNNING)) {
                activeDownloads.add(download);
            }
        }

        int size = activeDownloads.size();
        if (size > 0) {
            long speed = throttle / size;
            for (Download download : activeDownloads) {
                download.setThrottle(speed);
            }
        }
    }

    public void setThrottleBytesPerSecond(long maxBytesPerSecond) {
        this.throttle = maxBytesPerSecond;
        distributeSpeedThrottle();
    }

    private class DownloadManagerListenerHelper implements DownloadManagerListener {

        @Override
        public void onDownloadAdded(Download download) {
        }

        @Override
        public void onDownloadRemoved(Download download) {
        }

        @Override
        public void onDownloadStatusChange(DownloadEvent event) {
            distributeSpeedThrottle();
        }
    }
}
